<?php

require_once("../data/common.php");

        # $sql = "SELECT * FROM tracks  LEFT JOIN (users, users_devices, gps_data) ON (tracks.last_id = gps_data.id AND tracks.device_id=users_devices.id AND users_devices.user_id=users.id) ORDER BY created DESC, username;";


	$sql = "SELECT 
			tr.device_id AS device_id, 
			tr.first_id AS first_id, 
			tr.last_id AS last_id, 
			tr.track_id AS track_id, 
			u.username AS username, 
			tr.created AS created, 
			tr.start_place AS start_place, 
			tr.end_place AS end_place, 
			gd.time_received AS time_received 
		FROM 
			users u, 
			tracks tr, 
			users_devices ud, 
			gps_data gd 
		WHERE 
			(tr.last_id = gd.id AND
				tr.device_id=ud.id AND
				ud.user_id=u.id) AND 
			tr.privacy = 0 
		ORDER BY tr.created DESC, u.username;";
        $stmt = $dbh->prepare($sql);
        $stmt->execute();
	$rows = $stmt->fetchAll();
	print '<table border="0">';
	print "<tr><td>username</td><td>track time</td><td>start place</td><td>end place</td></tr>";
	foreach ($rows as $rs) {
		$start_place = $rs["start_place"];
		$end_place = $rs["end_place"];
		$now = time();
		$updated = strtotime($rs["time_received"]);
		if($start_place == null) $start_place = updateLocation("start_place",$rs["track_id"],$rs["first_id"]);
		if($end_place == null) {
			if (($now-$updated) > (60*10) ) {
				$end_place = updateLocation("end_place",$rs["track_id"],$rs["last_id"]);
			} else {
				$end_place = "TRACK NOT FINISHED";
			}
		}
		printf('<tr><td><a href="#" onclick="self.parent.viewtrack(\'%s\',%d,%d,%d,%d,\'%s\')">%s</a></td><td>%s</td><td>%s</td><td>%s</td></tr>',
			$site_url,
			$rs["device_id"],
			$rs["first_id"],
			$rs["last_id"],
			$rs["track_id"], 
			$rs["username"], 
			$rs["username"],
			$rs["created"], 
			$start_place, 
			$end_place);
	}
	print '</table>';


?>
